import time
from threading import Thread

from src.conf.conf_manager import ConfManager
from src.logger import Logger


class Timer:
    def __init__(self, conf: ConfManager, logger: Logger):
        self.__conf = conf
        self.__logger = logger

    def __do_timer_tasks(self):
        """按时间处理任务"""
        while True:
            time.sleep(1)
            for task in self.__conf.timer_task.content:
                try:
                    # 禁用时跳过
                    if not task.get("启用", True):
                        continue
                    now_day = time.localtime().tm_wday + 1
                    now_time = time.strftime("%H:%M:%S", time.localtime())
                    if now_day in task["每周"]:
                        if now_time in [s + ":00" for s in task["时间"]]:
                            self.__logger.add_cmd(task["执行命令"])
                except Exception as err:
                    print(f"[DLS][WARN][TASK] 异常的任务: {task} 原因: {err}")

    def start(self) -> None:
        """启动定时器"""
        thx = Thread(target=self.__do_timer_tasks, daemon=True)
        thx.start()
